<?php
/**
 *                          _ooOoo_
 *                         o8888888o
 *                         88" . "88
 *                         (| -_- |)
 *                         O\  =  /O
 *                      ____/`---'\____
 *                    .'  \|     |//  `.
 *                   /  \|||  :  |||//  \
 *                  /  _||||| -:- |||||-  \
 *                  |   | \\  -  /// |   |
 *                  | \_|  ''\---/''  |   |
 *                  \  .-\__  `-`  ___/-. /
 *                ___`. .'  /--.--\  `. . __
 *             ."" '<  `.___\_<|>_/___.'  >'"".
 *            | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *            \  \ `-.   \_ __\ /__ _/   .-` /  /
 *       ======`-.____`-.___\_____/___.-`____.-'======
 *                          `=---='
 *
 *==================================================
 *                  佛祖保佑        永无BUG
 *         佛曰:
 *                写字楼里写字间，写字间里程序员；
 *                程序人员写程序，又拿程序换酒钱。
 *                酒醒只在网上坐，酒醉还来网下眠；
 *                酒醉酒醒日复日，网上网下年复年。
 *                但愿老死电脑间，不愿鞠躬老板前；
 *                奔驰宝马贵者趣，公交自行程序员。
 *                别人笑我忒疯癫，我笑自己命太贱；
 *                不见满街漂亮妹，哪个归得程序员？
 *==================================================
 */

 
/**
 * 大营配置
 * @author  Don
 * @date    2019-05-22
 */

namespace App\Admin\Controllers\kly;

use App\Models\kly\Kly_camp;
use App\Models\kly\Kly_term;
use App\Models\kly\Kly_student;
use App\Models\Squad;
use DB;
use Encore\Admin\Widgets\Table;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
// use Encore\Admin\Grid\Displayers\Modal;


class Big_camp_configController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('大营');
            $content->description('配置');
            
            $content->body($this->grid()->render());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('大营');
            $content->description(trans('admin.edit'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('大营');
            $content->description(trans('admin.create'));

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Kly_camp::class, function (Grid $grid) {
            $grid->model()->where('camp_type','1');
            if (!Admin::user()->isAdministrator()) {
                $grid->model()->WhereRaw('find_in_set('.Admin::user()->id.',`leaders`)');
            }
            $grid->model()->orderBy('id', 'desc');
            $grid->name(trans('admin.name'));
            $grid->column('周期')->display(function(){
                $camp_term = Kly_term::find($this->term_id);
                return $camp_term->name."(".$camp_term->start_date."-".$camp_term->end_date.")";
            });
            $grid->squads('针对班级')->display(function($squads){
                $squads_arr = [];
                foreach ($this->squads as  $sv) {
                    array_push($squads_arr,Squad::where('id',$sv)->value('name'));
                }
                // dd($squads_arr);
                return $squads_arr;
            })->label('danger')->style('max-width:600px;word-break:break-all;');
            $grid->leaders('主负责人')->display(function($leaders){
                $leaders_arr = [];
                foreach ($this->leaders as  $lv) {
                    array_push($leaders_arr,DB::table('admin_users')->where('id',$lv)->value('username'));
                }
                return $leaders_arr;
            })->label('info');
            // $grid->teachers('老师')->display(function($teachers){
            //     $teachers_arr = [];
            //     foreach ($this->teachers as  $tev) {
            //         array_push($teachers_arr,DB::table('admin_users')->where('id',$tev)->value('en_name'));
            //     }
            //     return $teachers_arr;
            // })->label('primary');
            // $grid->tutors('班主任')->display(function($tutors){
            //     $tutors_arr = [];
            //     foreach ($this->tutors as  $tv) {
            //         array_push($tutors_arr,DB::table('admin_users')->where('id',$tv)->value('en_name'));
            //     }
            //     return $tutors_arr;
            // })->label('success');
            // $grid->tutors('主班主任')->display(function($tutors){
            //     return DB::table('admin_users')->where('id',$this->tutors)->value('en_name');
            // })->label('success');
            // $grid->aids('助理班主任')->display(function($aids){
            //     $aids_arr = [];
            //     foreach ($this->aids as  $tv) {
            //         array_push($aids_arr,DB::table('admin_users')->where('id',$tv)->value('en_name'));
            //     }
            //     return $aids_arr;
            // })->label('success');
            $grid->column('小营数')->display(function(){
                $small_camp_count = Kly_camp::where('pid',$this->id)->count();
                return '<a style="cursor:pointer;" href="small_camp_config?pid='.$this->id.'">'.$small_camp_count."</a>";
            })->link("small_camp_config?pid=1");
            $grid->column('人数')->display(function(){
                $students = Kly_student::where('big_camp_id',$this->id)->count();
                return '<a style="cursor:pointer;" href="kly_student_list?b_id='.$this->id.'">'.$students."</a>";
            });
            $grid->disableActions();
    //         $grid->actions(function ($actions) {
    //             $actions->disableView();
				// $actions->disableDelete();
				// $actions->disableEdit();
    //         });

            //禁用导出按钮
            $grid->disableExport();
            //禁用筛选按钮
            $grid->disableFilter();
            
            $grid->tools(function ($tools) { 
                //关闭批量删除 
                $tools->batch(function ($batch) { 
                    $batch->disableDelete(); 
                });
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Kly_camp::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->text('name','名称')->rules('required')->rules('required')->addElementLabelClass('must-input');
            $form->hidden('camp_type')->value('1');
            $terms =  Kly_term::where('status','1')->orderBy('id','desc')->select('id as term_id',DB::raw("concat(name,'【',start_date,'至',end_date,'】') as term_name"))->get();
            $term_arr=array();
            foreach($terms as $k => $v){
                $term_arr[$v->term_id] = $v->term_name;
            }
            $form->select('term_id','所属周期')->options($term_arr)->rules('required')->addElementLabelClass('must-input');
            $form->listbox('squads', '参与班级')->options(Squad::all()->pluck('name','id')->toArray())->rules('required')->addElementLabelClass('must-input');
            $all_admin_users = DB::table('admin_users')->pluck('username','id')->toArray();
            // $all_teachers = DB::table('admin_users as au')->join('admin_role_users as aru',function($join){
            //     $join->on('au.id','aru.user_id');
            // })->where('aru.role_id','4')->pluck('en_name','id')->toArray();
            // $all_tutors = DB::table('admin_users as au')->join('admin_role_users as aru',function($join){
            //     $join->on('au.id','aru.user_id');
            // })->where('aru.role_id','2')->pluck('en_name','id')->toArray();
            $all_admin_users = DB::table('admin_users')->pluck('username','id')->toArray();
            $form->multipleSelect('leaders', '主负责人')->options($all_admin_users)->rules('required')->addElementLabelClass('must-input');
            // $form->multipleSelect('teachers', '老师')->options($all_admin_users)->rules('required')->addElementLabelClass('must-input');
            // $form->select('tutors', '班主任')->options($all_admin_users)->rules('required')->addElementLabelClass('must-input');
            // $form->multipleSelect('aids', '助理班主任')->options($all_admin_users)->rules('required')->addElementLabelClass('must-input');
            //去掉添加/编辑表单的重置按钮
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
			//系统管理员配置好大营后,给当前大营的主负责人分配角色"苦令营大营负责人"
			$form->saved(function (Form $form) {
				//当前大营的主负责人数组
				$leaders = $form->leaders;
				//去掉为null的最后一个元素
				array_pop($leaders);
				
				//找出角色为"苦令营大营负责人"的角色ID
				$role_id = DB::table('admin_roles')->where('slug','kly_leader')->value('id');
				//分别给主负责人分配角色
				foreach($leaders as $v)
				{
					//判断主负责人是否已有此角色,有则不分配,无则分配
					if(DB::table('admin_role_users')->where(['role_id'=>$role_id,'user_id'=>$v])->count()==0)
					{
						DB::table('admin_role_users')->insert([
							'role_id' => $role_id,
							'user_id' => $v
						]);
					}
				}
			});
        });
    }
}